﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace UNSWThinkDBTool
{
   /// <summary>
   /// Windows form that is used to gather required details to connect to a database.
   /// </summary>
   public partial class ConnectForm : Form
   {
      private string username;
      private string password;
      private string ipAddress;
      private string port;
      private string dbName;

      private MainForm main;

      /// <summary>
      /// Default constructor for ConnectForm
      /// </summary>
      public ConnectForm()
      {
         InitializeComponent();
      }

      /// <summary>
      /// Alternate constructor for ConnectForm which references a MainForm which is required
      /// to peform connection related tasks.
      /// </summary>
      /// <param name="mainForm">
      /// MainForm reference is required so that a DBConnection can be set and various GUI
      /// changes can be performed.
      /// </param>
      public ConnectForm(MainForm mainForm)
      {
         InitializeComponent();

         main = mainForm;
      }

      private void connectButton_Click(object sender, EventArgs e)
      {
         username = usernameTextBox.Text;
         password = passwordTextBox.Text;
         ipAddress = ipTextBox.Text;
         port = portTextBox.Text;
         dbName = dbNameTextBox.Text;

         // create DBConnection object
         DBConnection tempConn = new DBConnection(ipAddress, port, username, password, dbName);

         // start connection
         bool result = tempConn.Connect();

         // perform necessary operations depending on result of connection attepmt
         if (result)
         {
            main.SetDBConnection = tempConn;
            main.ToggleConnectMenuLabel();
            main.Connected = result;
            this.DialogResult = DialogResult.OK;
            this.Close();
         }
         else
         {
            MessageBox.Show(tempConn.ResultMessage, "Unable to connect", MessageBoxButtons.OK, MessageBoxIcon.Error);
            main.Connected = result;
            this.DialogResult = DialogResult.Abort;
         }
      }
   }
}
